<template>
  <page-layout title="合同模板管理">
    <div class="contract-management">
      <a-row type="flex" justify="center" align="middle">
        <a-col :span="8">
          <a-form layout="inline">
            <a-form-item label="关键字">
              <a-input v-model="searchTemplateState.name" placeholder="请输入模板/项目名称" allow-clear>
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" icon=“search @click="onSearch">查询</a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="4" :offset="12" style="text-align:right;">
          <a-button type="primary" @click="onNewTemplate">
            <a-icon type="plus" />
            新建模板
          </a-button>
        </a-col>
      </a-row>
      <a-table class="contract-table" rowKey="id" :columns="columns" :data-source="dataSource" :scroll="{x:true}" :pagination="{
                    current: searchTemplateState.page,
                    pageSize: searchTemplateState.size,
                    total: total,
                    showLessItems: true,
                    onChange: onPageChange,
                    onShowSizeChange: onSizeChange,
                }">
        >
        <template slot="status" slot-scope="text, record">
          <a-badge v-if="record.status == '1'" color="green" text="启用" />
          <a-badge v-else color="red" text="禁用" />
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-space :size="2">
            <a class="ant-dropdown-link" @click="onDetail(record.id)">详情</a>
            <a-divider type="vertical" />
            <a class="ant-dropdown-link" @click="onEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="ant-dropdown-link" @click="onView(record.id)">查看模板</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定要删除该合同模板吗?" ok-text="确定" cancel-text="取消" @confirm="onConfirmDelete(record.id)">
              <a class="ant-dropdown-link">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
      <!-- 新建模板弹窗 -->
      <a-modal :title="nowTemplateType==0?'新增模板':'编辑模板'" v-model="isNewTemplate" :width="360" @ok="handleOk" @cancel="handleCancel(0)">
        <a-form-model ref="addTemplate" :model="templateForm" :rules="templateFormRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-model-item label="模板名称" prop="templateBaseName">
            <a-input v-model="templateForm.templateBaseName" placeholder="请输入模板名称" allow-clear />
          </a-form-model-item>
          <a-form-model-item label="适用项目" prop="projectBaseName">
            <a-select v-model="templateForm.projectBaseName" :rules="{ required: true, message: '必须选择适用项目！', trigger: 'change' }" placeholder="请选择适用项目" @change="onSelectChange" allow-clear>
              <a-select-option v-for="project in projectList" :key="project.projectId" :value="project.projectId + ' ' + project.projectName">{{ project.projectName }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="模板状态" prop="status">
            <a-switch v-model="templateForm.status" />
          </a-form-model-item>
          <a-form-model-item label="上传模板" prop="templateUrl">
            <a-upload accept=".pdf" :action="get_OSS_config" :file-list="fileList" :remove="onRemoveNotice" :customRequest="onUpdate" ref="onUpload">
              <a-button>
                <a-icon type="upload" v-if="fileList.length < 1" /> Click to upload
              </a-button>
            </a-upload>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <!-- 详情弹窗 -->
      <a-modal v-model="isContractDetail" title="合同详情" :width="360" @cancel="handleCancel(1)" footer :body-style="{ 'padding-top': '10px' }">
        <a-descriptions title=" " :column="1">
          <a-descriptions-item label="模板ID">{{ nowTemplate.id }}</a-descriptions-item>
          <a-descriptions-item label="模板名称">{{ nowTemplate.templateName }}</a-descriptions-item>
          <a-descriptions-item label="适用项目">{{ nowTemplate.projectBaseName }}</a-descriptions-item>
          <a-descriptions-item label="模板状态">{{ nowTemplate.status == 1 ? '启用' : '停用' }}</a-descriptions-item>
          <a-descriptions-item label="创建人">{{ nowTemplate.createBy }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ templateDetailCreateTime }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ templateDetailUpdateTime }}</a-descriptions-item>
        </a-descriptions>
      </a-modal>
    </div>
  </page-layout>
</template>

<script>
import PageLayout from '@/layouts/PageLayout';
import { transferDate, upLoadAliyun } from '@/utils/util';
import { get_OSS_config } from '@/services/api';
import { queryTemplate, addTemplate, deleteTemplate, templateDetail, template, uploadTemplate, queryProject } from '@/services/contract';
export default {
  name: 'contractManagement',
  components: { PageLayout },
  data () {
    return {
      total: 0,
      get_OSS_config: get_OSS_config,
      columns: [
        {
          title: '模板名称',
          dataIndex: 'templateName',
          width: 200,
          fixed: 'left',
          scopedSlots: { customRender: 'templateName' },
        },
        {
          title: '模板id',
          dataIndex: 'id',
          scopedSlots: { customRender: 'id' },
        },
        {
          title: '项目名称',
          dataIndex: 'projectBaseName',
          scopedSlots: { customRender: 'projectBaseName' },
        },
        {
          title: '模板状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          scopedSlots: { customRender: 'createBy' },
        },
        {
          title: '更新时间',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 260,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      dataSource: [],
      isNewTemplate: false,
      isContractDetail: false,
      nowTemplate: {},
      templateForm: {
        templateBaseName: '',
        projectBaseId: undefined,
        projectBaseName: undefined,
        originalFileName: "",
        templateUrl: "",
        status: true,
        code: '',
        id: '',
      },
      templateFormRules: {
        templateBaseName: [
          {
            required: true,
            message: '模板名称不允许为空！',
            trigger: 'blur',
          },
        ],
        status: [{ required: true, message: '必须选择模板状态！', trigger: 'change' }],
        projectBaseName: [{ required: true, message: '必须选择适用项目！', trigger: 'change' }],
        templateUrl: [{ required: true, message: '请上传合同模板！', trigger: 'blur' }],
      },
      searchTemplateState: {
        name: '',
        page: 1,
        size: 10,
      },
      nowTemplateType: 0,
      projectList: [],
      editTemplate: {},
      fileList: []
    };
  },
  computed: {
    templateDetailCreateTime () {
      return this.nowTemplate.createTime ? transferDate(this.nowTemplate.createTime, 2) : '';
    },
    templateDetailUpdateTime () {
      return this.nowTemplate.updateTime ? transferDate(this.nowTemplate.updateTime, 2) : '';
    },
  },
  methods: {
    onRemoveNotice () {
      this.fileList = [];
      this.templateForm.templateUrl = '';
      this.templateForm.originalFileName = '';
      this.templateForm.code = '';
    },
    onUpdate (info) {
      this.$message.warning('正在上传中......', 1)
      let fileType = info.file.name
      const type = fileType.substring(fileType.lastIndexOf('.'))
      if (!/.pdf/.test(type)) {
        this.$message.warning('只允许上传pdf模板！')
        return;
      }
      upLoadAliyun(info).then(res => {
        this.templateForm.originalFileName = fileType;
        this.templateForm.templateUrl = res.filePath
        this.fileList = []
        this.fileList.push({ uid: '-3', name: fileType, status: 'done', url: res.filePath, });
        // 上传合同模板换取模板code
        uploadTemplate({ url: res.filePath }).then(res1 => {
          let { code, data, msg } = res1.data;
          if (code == 200) {
            // progress.percent = 100;
            // info.onSuccess(res, info.file);
            this.$message.success("上传成功！")
            this.templateForm.code = data;
          } else {
            this.$message.error(msg)
          }
        });
        // let progress = { percent: 1 };
        // let speed = parseInt(100 / (info.file.size / 65000));
        // const intervalId = setInterval(() => {
        //   if (progress.percent < 100) {
        //     progress.percent += speed; //控制进度条速度
        //     info.onProgress(progress); //onProgress接收一个对象{ percent: 进度 }在进度条上显示
        //   } else {
        //     clearInterval(intervalId);
        //   }
        // }, 100);
      });
    },
    onSearch () {
      this.getTemplateList(this.searchTemplateState);
    },
    onNewTemplate () {
      this.nowTemplateType = 0;
      this.isNewTemplate = true;
      this.$refs.onUpload && (this.$refs.onUpload.sFileList = [])
      this.getProjectList();
    },
    onEdit (item) {
      this.nowTemplateType = 1;
      this.isNewTemplate = true;
      this.editTemplate = item;
      let { originalFileName, templateUrl, templateName: templateBaseName, projectBaseName, status, projectBaseId, eqbTemplateId: code } = this.editTemplate;
      this.fileList = []
      if (templateUrl) {
        this.fileList.push({ uid: '-3', name: originalFileName, status: 'done', url: templateUrl });
      }
      this.templateForm = { originalFileName, templateUrl, templateBaseName, projectBaseName, projectBaseId, code }
      this.templateForm.status = (status == 1 ? true : false)
      this.templateForm.id = item.id;
      this.getProjectList();
    },
    onView (id) {
      // 查看合同模板
      template({ id: id }).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          window.open(res.data.data, '_blank');
        } else {
          this.$message.error(msg)
        }
      });
    },
    onDetail (id) {
      // 合同模板详情
      templateDetail({ id: id }).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.nowTemplate = data;
        } else {
          this.$message.error(msg)
        }
      });
      this.isContractDetail = true;
    },
    onSelectChange (value) {
      this.templateForm.projectBaseId = value.split(' ')[0];
      this.templateForm.projectBaseName = value.split(' ')[1];
    },

    onConfirmDelete (id) {
      this.dataSource = this.dataSource.filter(val => val.id != id);
      // 删除合同模板
      deleteTemplate({ id: id }).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.$message.success(msg);
        } else {
          this.$message.error(msg)
        }
      });
    },
    handleOk () {
      let params = JSON.parse(JSON.stringify(this.templateForm));
      params.status = params.status ? 1 : 2
      this.$refs.addTemplate.validate(valid => {
        if (valid) {
          // 新增合同模板
          addTemplate(params).then(res => {
            let { code, data, msg } = res.data;
            if (code == 200) {
              this.isNewTemplate = false;
              this.$refs.addTemplate.resetFields();
              this.getTemplateList(this.searchTemplateState);
            } else {
              this.$message.error(msg)
            }
          });
        } else {
          return false;
        }
      });
    },
    handleCancel (i) {
      if (i == 0) {
        this.$refs.addTemplate.resetFields();
      }
    },
    /**
     * @description: 分页
     * @param {*} page
     * @param {*} pageSize
     * @return {*}
     */
    onPageChange (page, pageSize) {
      this.searchTemplateState.page = page;
      this.searchTemplateState.size = pageSize;
      this.getTemplateList(this.searchTemplateState);
    },
    onSizeChange (current, size) {
      this.searchTemplateState.page = 1;
      this.searchTemplateState.size = size;
      this.getTemplateList(this.searchTemplateState);
    },
    /**
     * @description: 获取模板列表
     * @param {*}
     * @return {*}
     */
    getTemplateList (params) {
      queryTemplate(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.dataSource = data.content;
          this.total = data.totalElements
          for (var i of this.dataSource) {
            i.createTime ? (i.createTime = transferDate(i.createTime, 2)) : '';
          }
        } else {
          this.$message.error(msg)
        }
      });
    },
    /**
     * @description: 获取项目下拉列表
     * @param {*}
     * @return {*}
     */
    getProjectList () {
      queryProject().then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.projectList = data;
        } else {
          this.$message.error(msg)
        }
      });
    },
  },
  mounted () {
    this.getTemplateList(this.searchTemplateState);
  },
};
</script>

<style scoped lang="less">
.contract-management {
  background: #fff;
  padding: 24px;
  .contract-table {
    margin-top: 24px;
  }
  /deep/.ant-table td {
    white-space: nowrap;
  }
}
</style>
